package cn.learn.office.excel_v3.write.sort;


import cn.learn.office.excel_v3.write.ExcelExportConfig;
import cn.learn.office.excel_v3.write.ExcelPosition;
import cn.learn.office.excel_v3.write.WriteExcelUtil;
import org.apache.poi.ss.usermodel.*;

import java.util.List;
import java.util.Map;

/**
 * 处理无序的hashMap集合的排序方法
 *
 * @author huangyezhan
 * @version 3.1
 * @date 2020年4月20日21:17:58
 */
public class MapColumnSort implements HandlerExcelColumnSort {

    /**
     * 处理自定义顺序的
     */
    @Override
    public void columnSort(ExcelExportConfig config, Sheet sheet) {
        Workbook                      workbook       = sheet.getWorkbook();
        Map<ExcelPosition, CellStyle> styleInstances = WriteExcelUtil.createStyleInstances(workbook);

        List<?> rowData = config.getContent();
        if (null != rowData && rowData.size() > 0) {
            //开始导入数据开始行数号（去掉表头的行数）
            int  startRowNum = config.getHeaderRowNum();
            Row  row         = null;
            Cell cell        = null;
            for (int i = 0; i < rowData.size(); i++) {
                row = sheet.createRow(i + startRowNum);
                // 列
                for (int j = 0; j < config.getColumnNum(); j++) {
                    Map<String, Object>          map        = (Map<String, Object>) rowData.get(i);
                    ExcelExportConfig.WriteOrder writeOrder = config.getWriteOrderKeys()[j];
                    Object                       o          = map.get(writeOrder.name());
                    // 值转换
                    if (null != writeOrder.valueMapping()) {
                        o = writeOrder.valueMapping().get(o);
                    }
                    // 值的格式化转换
                    if (null != writeOrder.format()) {
                        o = String.format(writeOrder.format(), o);
                    }
                    cell = row.createCell(j);
                    // 设置cell样式
                    WriteExcelUtil.setCellStyle(styleInstances, cell, config.getPositions()[j]);
                    if (null != o) {
                        WriteExcelUtil.writeContent(o, cell);
                    }
                }
            }
        }
    }

}

